<?php

namespace App\Http\Controllers;


use App\weekmodel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class weekcontroller extends Controller
{
    public function add(Request $request)
    {
        $name = $request['name'];
        $pwd = $request['pwd'];
        $file = $request->file("img");

        //new orm
        $fsp = new weekmodel();
        $fsp['name'] = $name;
        $fsp['pwd'] = $pwd;
        $fsp->save();
        $id = $fsp->id;

        //设置图片上传类型
        $type = ['jpeg', 'png'];
        if (!in_array($file->getClientOriginalExtension(), $type)) {
            dd("只能上传jpeg和png格式的图片");
        }
        //设置图片的路径
        $path = __DIR__ . '/../../../public/img' . intval($id / 1000);

        $a = $file->getClientOriginalExtension();//获取图片后缀名
        $filename = $id . "." . $a;    //拼接图片后缀
        $file->move($path, $filename);  //生成图片
        $img = $path .'/'. $filename;
        $fsp['img'] = $img;
        $a = $fsp->save();  //添加到图片
        if ($a) {
            return "<script>alert('添加成功');location.href='list';</script>";
        }
        return "<script>alert('添加失败');location.href='index';</script>";

    }

    public function list(Request $request)
    {
        $redis = Redis::connection();
        $datas = weekmodel::li();
//        dd($datas);
        $redis->set("data",$datas);
        $dataa = $redis->get("data");
        //调用模型层
        $data = weekmodel::li();

        if (!$redis->exists("data")==""){
        return view("list", ['data' => $data]);
        }else{
            //如果redis里有数据，就调用
            return view("list", ['data' => $dataa]);
        }

    }

    //获取图片
    public  function get(Request $request)
    {
        $id = $request['id'];
        $fsp = weekmodel::find($id);
        $img = $fsp['img'];
        return response()->file($img);
    }

    //下载图片
    public function gets(Request $request)
    {
        $id = $request['id'];
        $fsp = weekmodel::find($id);
        $img = $fsp['img'];
        return response()->download($img, $id . '.png');
    }


}
